<script setup>
import { reactive, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import planApi from "@/api/planApi";
import freeTestApi from "@/api/freeTestApi.js";
import constants from "@/utils/constants";
import Upload from "@/components/Upload.vue";
import planApplyProjectApi from "../../api/planApplyProjectApi";
import projectApi from "../../api/projectApi";
import tool from "@/utils/tool";

const searchForm = ref();
const searchFreeForm = ref();
const historyParams = history.state.params;

const searchModel = reactive({
  planId: historyParams.planId,
  gradeId: "",
});

const searchFreeModel = reactive({
  planId: historyParams.planId,
});

const uploadVisible = ref(false);
const uploadFreeTestVisible = ref(false);
const loading = ref(false);
const freeLoading = ref(false);
const printVisible = ref(false);

let uploadData = ref({
  planId: historyParams.planId,
});
let schoolList = ref([]);
let gradeClassesList = ref([]);
let classesList = ref([]);

let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search(current, pagination.pageSize);
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search(pagination.current, size);
  },
});

let freePagination = reactive({
  total: 0,
  current: 1,
  pageSize: 120,
  showPageSize: true,
  pageSizeOptions: [120, 320, 480, 960],
  showTotal: true,
  pageChange: (current) => {
    freePagination.current = current;
    searchFree();
  },
  pageSizeChange(size) {
    freePagination.pageSize = size;
    searchFree();
  },
});

const columns = [
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 150,
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
  },
  {
    title: "性别",
    slotName: "sex",
    width: 100,
  },

  {
    title: "年级",
    dataIndex: "gradeName",
    width: 100,
  },
  {
    title: "班级",
    dataIndex: "classesName",
    width: 100,
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
  },
  {
    title: "身份证号",
    dataIndex: "idNumber",
    width: 200,
  },
  {
    title: "IC卡号",
    dataIndex: "cardNo",
    width: 150,
  },
  {
    title: "录入时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "报名项目",
    dataIndex: "projectNames",
    width: 300,
    fixed: "right",
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];

const freeColumns = [
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 150,
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
  },
  {
    title: "性别",
    slotName: "sex",
    width: 100,
  },

  {
    title: "年级",
    dataIndex: "gradeName",
    width: 100,
  },
  {
    title: "班级",
    dataIndex: "classesName",
    width: 100,
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
  },
  {
    title: "项目名称",
    dataIndex: "projectName",
    width: 100,
  },
  {
    title: "原因",
    dataIndex: "reason",
    width: 100,
  },
  {
    title: "得分",
    dataIndex: "score",
    width: 100,
  },
  {
    title: "录入时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];

const data = ref([]);
const freeData = ref([]);

const schoolSelectChange = (schoolId) => {
  if (schoolId) {
    planApi
      .getGradeClassesList({
        planId: historyParams.planId,
        schoolId: schoolId,
      })
      .then((res) => {
        gradeClassesList.value = res;
      });
  } else {
    gradeClassesList.value = [];
    classesList.value = [];
    searchModel.classesId = "";
    searchModel.gradeId = "";
  }
};

const importApplyData = () => {
  uploadVisible.value = true;
};

const projects = ref([]);
const editData = ref({});
const showEditDiaglog = ref(false);

const editRecord = (record) => {
  showEditDiaglog.value = true;
  editData.value = Object.assign({}, record);
  searchPrj(record.gradeId, record.sex);
  if (record.projectNames) {
    editData.value.projectNameItems = record.projectNames.split(",");
  } else {
    editData.value.projectNameItems = [];
  }
};

const submitEditApply = () => {
  if (
    !editData.value.projectNameItems ||
    editData.value.projectNameItems.length == 0
  ) {
    Message.warning("请选择至少一个报项");
    return;
  }
  planApplyProjectApi
    .updateProjectNames({
      id: editData.value.id,
      studyCode: editData.value.studyCode,
      projectNames: editData.value.projectNameItems.toString(),
    })
    .then((res) => {
      search();
    });
};

const searchPrj = (gradeId, sex) => {
  var params = {
    pageNo: 1,
    pageSize: 10000,
    queryParam: {
      templateId: historyParams.templateId,
      gradeId: gradeId,
    },
  };
  projectApi.page(params).then((res) => {
    projects.value = res.records;

    projects.value.forEach((item) => {
      if (sex == "1" || sex == '男') {
        if (
          item.projectName == "800米" ||
          item.projectName == "一分钟仰卧起坐"
        ) {
          item.disabled = true;
        }
      } else if (sex == "2" || sex == '女') {
        if (item.projectName == "1000米" || item.projectName == "引体向上") {
          item.disabled = true;
        }
      }
    });
  });
};

const deleteRecord = (record) => {
  planApplyProjectApi
    .deleteApplyProject({
      id: record.id,
    })
    .then((res) => {
      search();
    });
};

const deleteFreeRecord = (record) => {
  freeTestApi
    .delete({
      id: record.id,
    })
    .then((res) => {
      searchFree();
    });
};

let permissions = tool.data.get("permissions");

const hasPermission = (code) => {
  return permissions.includes(code);
};

const changeSelectGrade = (gradeId) => {
  let gradeModel = gradeClassesList.value.find((grade) => {
    return grade.id == gradeId;
  });
  if (gradeModel && gradeModel.children && gradeModel.children.length > 0) {
    classesList.value = gradeModel.children;
  } else {
    searchModel.classesId = "";
    classesList.value = [];
  }
};

const getSchoolList = () => {
  planApi
    .getSchoolList({
      planId: historyParams.planId,
    })
    .then((res) => {
      schoolList.value = res;
    });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  planApplyProjectApi.queryPage(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const searchFree = () => {
  var params = {
    pageNo: freePagination.current,
    pageSize: freePagination.pageSize,
    queryParam: Object.assign({}, searchFreeModel),
  };
  freeLoading.value = true;
  freeTestApi.queryPage(params).then((res) => {
    freeData.value = res.records;
    freePagination.total = res.total;
    freeLoading.value = false;
  });
};

const refresh = () => {
  search();
};

const getNationName = (value) => {
  let nationItem = constants.nationList.find((res) => {
    return res.value == value;
  });
  return !nationItem ? "" : nationItem.label;
};

const reset = () => {
  searchForm.value.resetFields();
  searchModel.classesId = "";
  searchModel.gradeId = "";
};

const importFreeTestData = () => {
  uploadFreeTestVisible.value = true;
};

const changeTab = (key) => {
  if (key == 1) {
    search();
  } else {
    searchFree();
  }
};

const clearApplyData = () => {
  if (!historyParams.planId) {
    return;
  }
  planApplyProjectApi
    .clearData({
      planId: historyParams.planId,
    })
    .then((res) => {
      Message.success("清空成功");
      search();
    });
};

refresh();
getSchoolList();
</script>

<template>
  <div class="main-con">
    <div style="padding-bottom: 16px">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
        <a-breadcrumb-item>考试计划</a-breadcrumb-item>
        <a-breadcrumb-item>报名报项</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-tabs default-active-key="1" @change="changeTab" size="large">
      <a-tab-pane key="1" title="报名报项">
        <a-card>
          <a-row>
            <a-col :flex="1">
              <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 8 }"
                :wrapper-col-props="{ span: 16 }" label-align="left">
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item field="schoolId" label="学校">
                      <a-select v-model="searchModel.schoolId" placeholder="请选择学校" allow-clear
                        @change="schoolSelectChange">
                        <a-option v-for="school in schoolList" :value="school.id" :key="school.id"
                          :label="school.name"></a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item field="gradeId" label="年级/班级">
                      <a-space>
                        <a-select style="width: 120px" v-model="searchModel.gradeId" @change="changeSelectGrade"
                          placeholder="年级">
                          <a-option value="">全部</a-option>
                          <a-option v-for="item in gradeClassesList" :key="item.id" :value="item.id">{{ item.name
                          }}</a-option>
                        </a-select>
                        <a-select style="width: 120px" v-model="searchModel.classesId" placeholder="班级">
                          <a-option value="">全部</a-option>
                          <a-option v-for="classes in classesList" :key="classes.id" :value="classes.id">{{ classes.name
                          }}</a-option>
                        </a-select>
                      </a-space>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item field="name" label="学生姓名">
                      <a-input v-model="searchModel.name" placeholder="请输入姓名" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item field="sex" label="性别">
                      <a-select v-model="searchModel.sex" placeholder="请选择性别">
                        <a-option value="1">男</a-option>
                        <a-option value="2">女</a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item field="studyCode" label="学籍号">
                      <a-input v-model="searchModel.studyCode" placeholder="请输入学籍号" />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
            <a-divider style="height: 84px" direction="vertical" />
            <a-col :flex="'86px'" style="text-align: right">
              <a-space direction="vertical" :size="18">
                <a-button type="primary" @click="search">
                  <template #icon>
                    <icon-search />
                  </template>
                  查询
                </a-button>
                <a-button @click="reset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-card>
        <a-card>
          <div class="toolbar">
            <a-space>
              <a-button type="primary" @click="importApplyData">
                <template #icon>
                  <icon-upload />
                </template>
                导入报名报项
              </a-button>
              <a-popconfirm content="确认要清空所有报名报项数据吗？" @ok="clearApplyData">
                <a-button v-if="hasPermission('clearApplyData')" type="outline">
                  <template #icon>
                    <icon-delete />
                  </template>
                  清空报名报项
                </a-button>
              </a-popconfirm>
            </a-space>
          </div>
          <a-table :columns="columns" :loading="loading" :data="data" @page-change="pagination.pageChange"
            @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">
            <template #nation="{ record }">
              {{ getNationName(record.nation) }}
            </template>
            <template #sex="{ record }">
              {{ record.sex == "1" ? "男" : " 女" }}
            </template>
            <template #action="{ record }">
              <a-space>
                <a-button @click="editRecord(record)" type="text">修改报项</a-button>
                <a-popconfirm content="确认要删除该数据吗？" @ok="deleteRecord(record)">
                  <a-button type="text">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
      <a-tab-pane key="2" title="免考信息">
        <a-card>
          <a-row>
            <a-col :flex="1">
              <a-form ref="searchFreeForm" :model="searchFreeModel" :label-col-props="{ span: 8 }"
                :wrapper-col-props="{ span: 16 }" label-align="left">
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item field="schoolId" label="学校">
                      <a-select v-model="searchFreeModel.schoolId" placeholder="请选择学校" allow-clear
                        @change="schoolSelectChange">
                        <a-option v-for="school in schoolList" :value="school.id" :key="school.id"
                          :label="school.name"></a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item field="name" label="学生姓名">
                      <a-input v-model="searchFreeModel.name" placeholder="请输入姓名" />
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item field="sex" label="性别">
                      <a-select v-model="searchFreeModel.sex" placeholder="请选择性别">
                        <a-option value="1">男</a-option>
                        <a-option value="2">女</a-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item field="studyCode" label="学籍号">
                      <a-input v-model="searchFreeModel.studyCode" placeholder="请输入学籍号" />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
            <a-divider style="height: 84px" direction="vertical" />
            <a-col :flex="'86px'" style="text-align: right">
              <a-space direction="vertical" :size="18">
                <a-button type="primary" @click="searchFree">
                  <template #icon>
                    <icon-search />
                  </template>
                  查询
                </a-button>
                <a-button @click="searchFreeForm.value.resetFields()">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-card>
        <a-card>
          <div class="toolbar">
            <a-space>
              <a-button type="outline" @click="importFreeTestData">
                <template #icon>
                  <icon-upload />
                </template>
                导入免考学生
              </a-button>
            </a-space>
          </div>
          <a-table :columns="freeColumns" :loading="freeLoading" :data="freeData"
            @page-change="freePagination.pageChange" @page-size-change="freePagination.pageSizeChange"
            :pagination="freePagination" :bordered="false">
            <template #sex="{ record }">
              {{ record.sex == "1" ? "男" : " 女" }}
            </template>
            <template #action="{ record }">
              <a-space>
                <a-popconfirm content="确认要删除该数据吗？" @ok="deleteFreeRecord(record)">
                  <a-button type="text">删除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
  </div>

  <a-modal v-model:visible="uploadFreeTestVisible" title="导入免考学生数据">
    <a-space direction="vertical" style="width: 100%; text-align: center">
      <div style="color: #999">
        暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传
      </div>
      <a-button type="link" href="/学生免考.xlsx" style="margin-bottom: 10px">导入免考学生模板下载</a-button>
      <Upload :uploadData="uploadData" :draggable="true" accept=".xls,.xlsx"
        action="/admin/v1/plan/importFreeTestData" />
    </a-space>
  </a-modal>

  <a-modal v-model:visible="uploadVisible" title="导入报名报项">
    <a-space direction="vertical" style="width: 100%; text-align: center">
      <div style="color: #999">
        <div style="color: red;">本平台为互联网非涉密平台，严禁处理、传输国家秘密、工作秘密及敏感信息。请确认扫描、传输的文件资料不涉及上述信息。</div>
        <div>暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传</div>
      </div>
      <a-button type="link" href="/报名报项导入模板.xlsx" style="margin-bottom: 10px">报名报项导入模板下载</a-button>
      <Upload :uploadData="uploadData" :draggable="true" accept=".xls,.xlsx" action="/admin/v1/plan/apply/import" />
    </a-space>
  </a-modal>

  <a-modal v-model:visible="showEditDiaglog" title="修改报名报项" @ok="submitEditApply">
    <a-form :model="editData">
      <a-form-item label="原报项">
        <a-input v-model="editData.projectNames" disabled></a-input>
      </a-form-item>
      <a-form-item label="修改报项">
        <a-select v-model="editData.projectNameItems" placeholder="请选择" :multiple="true">
          <a-option v-for="prj in projects" :disabled="prj.disabled" :key="prj.projectName" :value="prj.projectName"
            :label="prj.projectName"></a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style>
@page {
  size: auto;
  margin: 0mm;
}
</style>
